#include "composite_goal.h"

using namespace spsu_art;

coposite_goal::process_subgoals() {

    //remove all subgoals until we find one that is either active or inactive
    while(!subgoal.empty()) {

        if(subgoals.front()->is_active() || subgoals.front()->is_inactive())
            break;

        subgoals.front()->terminate();
        delete subgoals.front();
        subgoals.pop_front();

    } //end while

    //if there are no subgoals left then return complete
    if(subgoals.empty())
        return G_complete;

    //activate the goal if it is inactive so it can plan
    if(subgoals.front()->is_inactive())
        subgoals.front()->activate();

    //tell the goal to process
    subgoals.front()->process();

    //if the front goal is complete but there are more subgoals then return
    //active
    if(subgoals.front()->is_complete() || subgoals.size() > 1)
        return G_active;

    //return the status of the front goal
    return subgoals.front()->get_status();

} //end process_subgoals

composite_goal::remove_subgoals() {

    for(std::list<goal*>::iterator iter = subgoal.begin();
            iter != subgoal.end();
            ++iter) {

        (*iter)->terminate();
        delete *iter;
    } //end for

    subgoals.clear();

} //end remove_subgoals

composite_goal::add_subgoal(goal* subgoal) {
    subgoals.push_back(subgoal);
} //end add_subgoal

composite_goal::push_subgoal(goal* subgoal) {
    subgoals.push_front(subgoal);
} //end push_subgoal

composite_goal::is_composite() {
    return true;
} //end is_composite

composite_goal::forward_message(const telegram& message) {

    bool handled = false;

    //if there is nothing to send the message to just return
    if(subgoals.empty())
        return handled;

    //send the message up the heirarchy to the next goal
    if(subgoals.front()->is_composite())
        handled = forward_message(message);

    //the other goals failed to handle the message so this will give it a go
    if(!handled)
        handled = handle_message(message);

    return handled;
} //end forward_message 
